package com.cs.store.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cs.store.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Controller
public class PayController {
    @Autowired
    private IOrderService iOrderService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //    @Autowired
//    DonaItemService donaItemService;
//    @Autowired
//    DonaService donaService;
    //appid
    private final String APP_ID = "9021000122696753";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDFBWHH0HvIu4BWezV2WJlm1iJ6AGrpsoKm8Dm3VuZFUlykM3vj+u0eME1zTHiGXvVu2qxcZbNfnfWDEQBykDHKyTd3szrMkCv2eojCG45mgpD+qGavUiJy0KWmnMh4AmZDIJYZbVUcdrz/qREI/TyC7PD3I8aMnvm++7IQHt3eYDZSs5An+q5mAU/2J9Hmb1JzXEZxYqw/OD/cWGImSkHnKURE+9sTeQu4iP5WsBv+bMZsK6Yz3qd9mY6NHzzqZXvR8kZpSZ//91jIAnpjVNg6hNjch4EFLIKSjxJybxXaVY2MvFDaqA3D9q8a4nzeTG+I0PfeIPvf7nuUpvlauomXAgMBAAECggEAREpFRjkhbsZvCYrTUR4MrfRzJs6WQEK7vpltp/ra/hQ6QEAIJVGIdvpPHjPXYtvvPmlVbQFjVzUtMCzods08NQnhy/+31cfzNQ/r7zwV87o1/87nK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z+ZIXogrxUA==";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhDvk6KhNLGO722oI2MqFvkEsp4VUbxnVpyHUPGLf5Poifsj30j/mCjomzQt9+0RgB/ezernEleJRuHA9tU68e0lbWZL8oIKAJz/JIotAnLSZcixofUZ/bfM8K9hi9HSsXDxseApZ9op88CZ0qKlP7yRiysJrPFxl8RK5xkDh9+IzemxufFZPTlMgma63y04x0xmiAoGzHvICGu/gg4Gqav1+itO4g1qcxWhAfyAkydBHeFLxfqiCjgB1xk1otO56WbCq0a+TZo7Pg+keqftOz1Ostn63jNTB30A6q9FBkNv2ZN/tlAvwJvwA07Wbk4tFR6aE/ZDwojTvu9NU5aK4sQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://localhost:8080/user";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:10004/returnUrl";

    @ResponseBody
    @RequestMapping("/pay/alipay")
    public String alipay(HttpSession session, Model model,
                         @RequestParam("dona_money") float dona_money,
                         @RequestParam("dona_id") int dona_id,
                         @RequestParam("order_num") String OrderNum,
                         @RequestParam("store_id") Long StoreId,
                         @RequestParam("username") String username) throws AlipayApiException {
        //把dona_id项目id 放在session中
        session.setAttribute("dona_id", dona_id);

        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(OrderNum, dona_money, StoreId, username, "ghjk");
    }

    /*
    参数1：订单号
    参数2：订单金额
    参数3：订单名称
     */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo, Float totalAmount, Long StoreId, String username, String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"store_id\":\"" + StoreId + "\","
                + "\"username\":\"" + username + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

    @RequestMapping("/returnUrl")
    public String returnUrlMethod(HttpServletRequest request, HttpSession session, Model model, HttpServletResponse resp) throws AlipayApiException, UnsupportedEncodingException {

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

            System.out.println("商户订单号=" + out_trade_no);
            System.out.println("支付宝交易号=" + trade_no);
            System.out.println("付款金额=" + money);

            //在这里编写自己的业务代码（对数据库的操作）
            Map<String, String> map = new HashMap<>();
            map.put("out_trade_no", out_trade_no);
            map.put("trade_no", trade_no);
            map.put("money", String.valueOf(money));
            //跳转到提示页面（成功的提示页面）
//            model.addAttribute("flag",1);
//            model.addAttribute("msg","支持");
            try {
                iOrderService.updateOrder("已支付",out_trade_no);
                iOrderService.delCarAfOrder(out_trade_no);
                stringRedisTemplate.delete("order_" + out_trade_no);   //订单从缓存中删除
                resp.sendRedirect("http://localhost:8080/#/user/goods");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "common/payTips";
        } else {
            //跳转到提示页面（失败的提示页面）
            model.addAttribute("flag",0);
            model.addAttribute("msg","支付失败");
            return "common/payTips";
        }

    }
}